/* 
	Scripting Engine to allow scriptable gameplay elements

	by Julian Williams
	July 14, 2010
*/

#include <iostream>
using namespace std;

#include "ScriptEngine.h"
#include "scriptmath.h"
#include "scriptstring.h"


ScriptEngine aScriptEngine;

asIScriptEngine * engine;



//Error message callback function
void MessageCallback( const asSMessageInfo *msg, void *param)
{
	const char *type = "ERR ";

	if( msg->type == asMSGTYPE_WARNING)
	{
		type = "WARN";
	}else if( msg->type == asMSGTYPE_INFORMATION )
	{
		type = "INFO";
		printf("%s ( %d, %d) : %s : %s\n", msg->section, msg->row, msg->col, type, msg->message);
		system("Pause");
	}
}//EoF




bool ScriptEngine::Create()
{
	//Create Script Engine
	 engine = asCreateScriptEngine( ANGELSCRIPT_VERSION );
	 if( engine == 0 )
	 {
		cout << "Failed to create Angel Script engine." << endl;

		return false;
		
	 }
		 //set message callback function
		 engine->SetMessageCallback(asFUNCTION(MessageCallback), 0, asCALL_CDECL);


		//Register Math Functions
		// RegisterScriptMath( engine );

		//Register String Type
		// RegisterScriptString( engine );
		 return true;
}//EoF




//-----------------------------------------------------------------------------
// Name:	LoadScript()	[global function]
// Desc:	Reads a file specified by "filename" parameter and creates a new 
//			Angelscript Section with the name specified by "module" parameter.
//-----------------------------------------------------------------------------
int ScriptEngine::LoadScript(string filename, const char * module)
{
	// Read the entire script file
	FILE * pFile = fopen(filename.c_str(), "rb");
	if( pFile == 0 )
	{
		printf("Failed to open the script file.\n");
		return -1;
	}

	// Find the length of the script file
	fseek(pFile, 0, SEEK_END);
	int len = ftell(pFile);
	fseek(pFile, 0, SEEK_SET);

	// On Win32 it is possible to do the following instead
	// int len = _filelength(_fileno(f));

	string code;
	code.resize(len);

	// Read length of script file
	size_t c = fread(&code[0], len, 1, pFile);
	fclose(pFile);

	if( c == 0 ) 
	{
		printf("Failed to load script file (Empty).\n");
		return -1;
	}

	// Give the code to the script engine
	int nRet = engine->GetModule(NULL)->AddScriptSection(filename.c_str(), code.c_str(), len,  false);
	if( nRet < 0 ) 
	{
		printf("An error occured while adding the script section.\n");
	}

	// At this point the engine has copied the code to an 
	// internal buffer so we are free to release the memory we 
	// allocated. 

	// We can also add other script sections if we would like.
	// All script sections will be compiled together as if they
	// where one large script. 

	return nRet;
}//EoF




//Destroy Engine
void ScriptEngine::Destroy()
{
	SAFE_RELEASE(engine);
}